<?php

namespace app\api\controller\v41;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\zl6\Zl6Meditation;
use app\common\cachemodel\zl6\Zl6MeditationSection;
use app\common\cachemodel\zl6\Zl6MeditationSubscribe;
use app\common\cachemodel\ZlcrTag;
use app\common\cachemodel\ZlUserVip;
use think\response\Json;

class Meditate extends Auth2
{
    // 栏目信息
    protected $category = [
        [
            'type' => 0,
            'name' => '推荐'
        ],
        [
            'type' => 1,
            'name' => '专题'
        ],
    ];

    /**
     * 冥想课程栏目列表
     * @return Json
     * @throws \Exception
     */
    public function getList()
    {
        $type = input('type/d', 0);
        $page = input('page/d', 1);
        if (!isset($this->category[$type]))
        {
            return show(config('code.error'), '请求异常，请稍后再试');
        }
        if ($page < 1)
        {
            $page = 1;
        }
        $limit = $type === 0 ? 15 : 1000;
        $zl6MeditationModel = new Zl6Meditation();
        $pageData = $zl6MeditationModel->getPageDatas($this->user['id'] ?? 0, $type + 1, $page, $limit);
        $pageData['tab_list'] = $this->category;

        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 冥想课程详情
     * @return Json
     * @throws \Exception
     */
    public function getDetail()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常，请稍后再试');
        }
        $uid = $this->user ? $this->user['id'] : 0;
        $zl6MeditationModel = new Zl6Meditation();
        $zlcrTagModel = new ZlcrTag();
        $meditationInfo = $zl6MeditationModel->getInfoById($id, ['category_type', 'ability_tids', 'cate_tid', 'desc', 'type', 'is_vip_free', 'end_time', 'start_time', 'base_num', 'sub_num', 'remark', 'price', 'cover_img', 'share_img', 'title', 'description']);

        $nowTime = $this->request->time();
        $tagIds = $meditationInfo['ability_tids'];
        if ($meditationInfo['cate_tid'])
        {
            $tagIds[] = $meditationInfo['cate_tid'];
        }
        $tagListInfo = $zlcrTagModel->batchGetInfoByIds($tagIds);
        $tagList = [];
        if ($meditationInfo['cate_tid'] && isset($tagListInfo[$meditationInfo['cate_tid']]) && $tagListInfo[$meditationInfo['cate_tid']])
        {
            $tagList[] = [
                'name' => $tagListInfo[$meditationInfo['cate_tid']]['tag_name'],
                'icon' => $tagListInfo[$meditationInfo['cate_tid']]['templet_url'],
            ];
        }
        foreach ($meditationInfo['ability_tids'] as $tid)
        {
            if (isset($tagListInfo[$tid]) && $tagListInfo[$tid])
            {
                $tagList[] = [
                    'name' => $tagListInfo[$tid]['tag_name'],
                    'icon' => $tagListInfo[$tid]['templet_url'],
                ];
            }
        }
        $desList = $meditationInfo['desc'] ? [$meditationInfo['desc']] : [];
        $desList[] = $meditationInfo['type'] === 1 ? '大众冥想' : '半定制冥想';

        if ($meditationInfo['is_vip_free'] === 1)
        {
            if ($this->user)
            {
                $vipLevel = (new ZlUserVip())->getUserVipLevel($this->user['id']);
                $isVip = $vipLevel > 0;
            } else
            {
                $isVip = false;
            }
            if (!$isVip)
            {   // 不是VIP
                $recommendVip = [
                    'icon' => '/test/meditation/icon_recommend_vip.png',
                    'title' => '小行星会员',
                    'desc' => '开通可免费解锁全部，参与定期活动',
                    'btn_name' => '开通会员',
                ];
            }
        }
        $subInfo = [];
        $isStart = true;
        if ($meditationInfo['end_time'] > 0)
        {
            switch (true)
            {
                case $nowTime < $meditationInfo['start_time'] :
                    // 未开始
                    $tip1 = '暂未开始 · ' . date('m月d日 H:i', $meditationInfo['start_time']) . ' ～ ' . date('m月d日 H:i', $meditationInfo['end_time']);
                    $subNum = $meditationInfo['base_num'] + $meditationInfo['sub_num'];
                    if ($this->user && (new Zl6MeditationSubscribe())->isSubscribe($uid, $id))
                    {   // 已登陆 && 已订阅
                        $subInfo = [
                            'content' => "当前已预约，{$subNum}人预约",
                            'btn_name' => '取消预约',
                            'btn_type' => 2,
                        ];
                    } else
                    {   // 未订阅
                        $subInfo = [
                            'content' => "{$subNum}人预约",
                            'btn_name' => '立即预约',
                            'btn_type' => 1,
                        ];
                    }
                    $isStart = false;
                    break;
                case $nowTime > $meditationInfo['start_time'] && $nowTime < $meditationInfo['end_time'] :
                    // 进行中
                    $tip1 = '进行中 · ' . date('m月d日 H:i', $meditationInfo['end_time']) . ' 后结束';
                    $subInfo = [
                        'content' => ($meditationInfo['base_num'] + $meditationInfo['sub_num']) . '人正在参与…',
                        'btn_name' => '',
                        'btn_type' => 0,
                    ];
                    break;
                default :   // 已结束
                    $tip1 = '已结束 · ' . date('m月d日 H:i', $meditationInfo['start_time']) . ' ～ ' . date('m月d日 H:i', $meditationInfo['end_time']);
                    $subInfo = [
                        'content' => $meditationInfo['remark'],
                        'btn_name' => '',
                        'btn_type' => 0,
                    ];
            }
        }
        $mType = $meditationInfo['category_type'] === 1 ? 2 : 1;   // 课程类型 1=>普通课程 2=>十二星座课程
        if (!(float)($meditationInfo['price']) || ($meditationInfo['is_vip_free'] === 1 && ($isVip ?? false)))
        {   // 免费 | 支持vip免费 且 用户是VIP
            $isVipUnlock = true;
        } else
        {   // 付费
            $isVipUnlock = false;
        }
        // 是否支持VIP免费
        $isVipFree = $meditationInfo['is_vip_free'] === 1;
        $chapterData = (new Zl6MeditationSection())->getMeditionSectionListData($id, $mType, $uid, $isVipUnlock, $subInfo, $isVipFree);
        if (isset($recommendVip) && $recommendVip && isset($chapterData[0]['status']) && $chapterData[0]['status'] === 0)
        {   // 未解锁 不显示
            $recommendVip = null;
        }
        if (!$isStart)
        {   // 未开始
            foreach ($chapterData as $key => $item)
            {
                foreach ($item['list'] as $k => $v)
                {
                    $chapterData[$key]['list'][$k]['status'] = 2;  // 未开始
                }
            }
        }
        $resData = [
            'img' => $meditationInfo['cover_img'],
            'share_img' => $meditationInfo['share_img'],
            'title' => $meditationInfo['title'],
            'desc' => $desList,
            'tag_list' => $tagList,
            'content' => $meditationInfo['description'],
            'type' => $mType,
            'chapter_data' => $chapterData,
            'recommend_vip' => $recommendVip ?? null,
            'tip1' => $tip1 ?? '',
        ];

        return show(config('code.success'), '请求成功', $resData);
    }
}
